from datetime import datetime
import os
import time

from PIL import Image
from django.core.paginator import Paginator
from django.http import HttpResponse
from django.shortcuts import render
from django.db.models import Q

from common.models import Shop

def index(request,pIndex):
    '''浏览信息'''
    umod = Shop.objects
    list = umod.all()
    mywhere = []
    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword", None)

    if kw:
        list = umod.filter(Q(name__contains=kw) | Q(phone__contains=kw))
        mywhere.append("keyword=" + kw)
    else:
        list = umod.filter()

    # 分页逻辑
    if pIndex == '':
        pIndex = '1'
    pIndex = int(pIndex)
    p = Paginator(list,3)
    maxpages = p.num_pages  # 最大页数

    # 判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1

    list2 = p.page(pIndex)
    plist = p.page_range

    context = {'shopList': list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages, 'mywhere': mywhere}
    return render(request,"myadmin/shop/index.html",context)

def add(request):
    '''添加信息'''
    return render(request,"myadmin/shop/add.html")


def insert(request):
    '''执行增加'''
    try:
        # 判断并执行图片上传处理,店铺封面
        myfile_cover = request.FILES.get("cover_pic", None)
        if not myfile_cover:
            return HttpResponse("没有上传文件信息！")
        # 以时间戳命名一个新图片名称
        filename_cover = str(time.time()) + "." + myfile_cover.name.split('.').pop()
        destination_c = open(os.path.join("./static/uploads/shop/", filename_cover), 'wb+')
        for chunk_c in myfile_cover.chunks():  # 分块写入文件
            destination_c.write(chunk_c)
            destination_c.close()

        # 判断并执行图片上传处理,店铺logo
        myfile_banner = request.FILES.get("banner_pic", None)
        if not myfile_banner:
            return HttpResponse("没有上传文件信息！")
        # 以时间戳命名一个新图片名称
        filename_banner = str(time.time()) + "." + myfile_banner.name.split('.').pop()
        destination_b = open(os.path.join("./static/uploads/shop/", filename_banner), 'wb+')
        for chunk_b in myfile_banner.chunks():  # 分块写入文件
            destination_b.write(chunk_b)
            destination_b.close()

        # 获取商品信息并执行添加
        ob = Shop()
        ob.name = request.POST['name']
        ob.phone = request.POST['phone']
        ob.address = request.POST['address']
        ob.cover_pic = filename_cover
        ob.banner_pic = filename_banner
        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = ob.create_at
        ob.save()
        context = {'info': '添加成功！'}
    except Exception as err:
        print(err)
        context = {'info': '添加失败！'}
    return render(request, "myadmin/info.html", context)

def edit(request,sid):
    '''加载编辑页面信息'''
    try:
        ob = Shop.objects.get(id = sid)
        context={"shop":ob}
        return render(request,"myadmin/shop/edit.html",context)
    except Exception as err:
        print(err)
        context = {"info":"没有找到店铺信息！"}
        return render(request,"myadmin/info.html",context)

def update(request,tid):
    '''执行编辑信息'''
    pass
    try:
        ob = Shop.objects.get(id = tid)
        ob.status = request.POST['status']
        ob.save()
        context = {"info":"修改成功！"}
    except Exception as err:
        print(err)
        context = {"info":"修改成功！"}
    return render(request,"myadmin/info.html",context)